<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Article extends Base_Controller {

    public $articlesum = 0;
    public $limit = 5;
    public $page = 0;

    public function add() {
        $this->load->view('public/head');
        $this->load->view('pages/addarticle');
    }

    public function lists() {

        $this->page = $this->uri->segment(3);
        $query = $this->db->select('*')->order_by('id DESC')->get('qbjh_article');
        $list = $query->result_array();
        $this->articlesum = count($list);

        $this->load->library('pagination');
        $config['base_url'] = site_url('article/lists');
        $config['first_link'] = '首页';
        $config['last_link'] = '末页';
        $config['next_link'] = '>>';
        $config['cur_tag_open'] = '<span class="current">';
        $config['cur_tag_close'] = '</span>';
        $config['prev_link'] = '<<';
        $config['total_rows'] = $this->articlesum;
        $config['per_page'] = $this->limit;
        $this->pagination->initialize($config);
        $this->data['currentpage'] = $this->page;
        $query = $this->db->select('*')->order_by('id DESC')->limit($this->limit, $this->page)->get('qbjh_article');
        $this->data['articlelist'] = $query->result_array();
        $this->load->view('public/head', $this->data);
        $this->load->view('pages/articlelist');
    }

    public function adding() {
        $redata = $this->httpcode;
        $tid = $this->input->post('tid');
        $title = $this->input->post('title');
        $brief = $this->input->post('brief');
        $thumb = $this->input->post('thumb');
        $content = $this->input->post('content');
        $author = $this->input->post('author');
        $readamount = $this->input->post('readamount');

        $article = [
            'tid' => $tid,
            'title' => $title,
            'brief' => $brief,
            'thumb' => 'uploads/media/' . $thumb,
            'content' => $content,
            'author' => $author,
            'readamount' => $readamount,
            'createtime' => date('Y-m-d H:i:s')
        ];
        $redata['article'] = $article;

        $this->db->insert('qbjh_article', $article);
        if ($this->db->affected_rows()) {
            $redata['errno'] = 666;
            $redata['error'] = '添加文章成功';
        } else {
            $redata['errno'] = 600;
            $redata['error'] = '添加文章失败';
        }
        echo json_encode($redata);
    }

    public function del() {
        $redata = $this->httpcode;
        $id = $this->input->post('id');
        $this->db->delete('qbjh_article', ['id' => $id]);
        if ($this->db->affected_rows()) {
            $redata['errno'] = 666;
            $redata['error'] = '删除成功';
        } else {
            $redata['errno'] = 600;
            $redata['error'] = '删除失败';
        }
        echo json_encode($redata);
    }

}
